package com.lanju.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.Community;

@Repository
public class AreaCommunityDao{
	
	@PersistenceContext(unitName = "financialmarketingUnit")
	private EntityManager entityManager;


	public int addAreaCommunity(Community c){
		int result=0;
		try {
			entityManager.persist(c);
			result=1;
		} catch (Exception e) {
			result=0;
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 根据主键id获取小区详情
	 * @param community_id
	 * @return
	 */
	public Community getAreaCommunityDetail(Integer community_id){
		try {
			Community c=entityManager.find(Community.class, community_id);
			return c;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public List<Community> getAreaCommunityList(Map<String, Object> param){
		try {
			StringBuffer sql=new StringBuffer();
			sql.append("from Community where 1=1 ");
			Query query=entityManager.createQuery(sql.toString());
			if(param.get("offset") !=null){
				query.setFirstResult(Integer.valueOf(param.get("offset").toString())).setMaxResults(Integer.valueOf(param.get("pageSize").toString()));
			}
			if(!StringUtils.isEmpty(param.get("city_name"))){
				sql.append(" and city_name='"+param.get("city_name").toString()+"'ss");
			}
			List<Community> list=query.getResultList();
			return list;
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public long getAreaCommunityListCount(Map<String, Object> param){
		try {
			StringBuffer sql=new StringBuffer();
			sql.append("select count(*) from Community");
			Query query=entityManager.createQuery(sql.toString());
			long count=(long) query.getSingleResult();
			return count;
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return 0;
		}
	}
}
